#!/usr/bin/perl

##############################################################
#
#Purpose: To execute some commands on a set of planet lab nodes.
#
#Usage: pl_exec.pl
#		-h <host_file>
#		-f <file containing list of cmds to be exec>
#		-p <path in planetlab node>
#		-u <user name>
#
##############################################################

use strict 'vars';
package main;

use Getopt::Std;

my $ssh_options = "-o \"ConnectTimeout=20\"";

use vars qw($opt_h $opt_f $opt_u $opt_p);

#get command line options
getopts('f:h:u:p:');
if ($opt_h eq "" || $opt_f eq "" || $opt_p eq "") {
    die "Usage: pl_exec.pl -h <host_file> -f <cmd_file> -u <username> -p <path>\n";
}
if ($opt_u eq "") {
    $opt_u = "ucb_i3";
}

#concatenate file/dir names
my $cmd, my $cmdlist = "cd $opt_p; ";
open (CMDFILE, $opt_f) || die "Cannot open list of commands\n";
while ($cmd = <CMDFILE>) {
    chomp $cmd;
    if ($cmd =~ /^\s*#/) {
	print "Ignoring comment - $cmd\n";
    } else {
	$cmdlist = $cmdlist.$cmd."; ";
    }
}

#go over the list of hosts
my %hosts = (), my $host;
open (HOSTFILE, $opt_h) || die "Cannot open host file\n";
while ($host = <HOSTFILE>) {
    chomp $host;
    if ($host =~ /^\s*#/) {
	print "Ignoring comment - $host\n";
    } else {
	$hosts{$host} = 1;
    }
}

#ssh
my $i;
foreach $host(keys %hosts) {
    $i ++;
    print $host."\n";
    my $cmd = "ssh $ssh_options $opt_u\@$host \"$cmdlist\"";
    print "$cmd\n";
    system($cmd);
    
    if ($i %20 == 0) {
	sleep 10;
    }
    
    print "\n";
}
